<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 卡片区域 -->
         <el-row :gutter="20">
          <el-col :span="8">
            <el-input @clear="getUserList" clearable v-model="queryData.query" placeholder="请输入内容" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <!-- data: 将整个表格的数据交给table组件 -->
        <!-- border：添加纵向边框 -->
        <!-- stripe：各行变色 -->
        <!-- prop：控制每一列渲染的数据字段名 -->
        <el-table :data="users" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
         <el-table-column label="状态">
           <!-- 通过slot-scope来接收组件暴露的数据 el-table-column内部已经写好了<solt :row="item"></solt>-->
            <template slot-scope="scope">
              <el-switch
              v-model="scope.row.mg_state"
              @change="stateChange(scope.row)"
              active-color="gold"
              inactive-color="silver">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <!-- 包裹元素 -->
            <template slot-scope="scope">
              <el-button @click="editDialog(scope.row)" size="mini" type="primary" icon="el-icon-edit" circle></el-button>
              <el-button @click="deleteUser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete" circle></el-button>
              <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
                <el-button @click="setRole(scope.row)" size="mini" type="warning" icon="el-icon-setting" circle></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      @close="resetAddForm"
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%">
      <el-form :model="addForm" :rules="addRule" ref="addFormRef" label-width="70px">
        <!-- prop 表示使用data中定义的检验规则 -->
        <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog
      @close="resetEdit"
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%">
      <!-- :model=""用来定义整个表单的数据 -->
      <el-form :model="editForm" :rules="editRule" ref="editFormRef" label-width="80px">
        <!-- prop 表示使用data中定义的检验规则 -->
        <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      @close="closesetRoles"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <p>当前的用户：{{ currentUser.username }}</p>
      <p>当前的角色：{{ currentUser.role_name }}</p>
      <div>
        分配新角色
        <el-select v-model="selectValue" placeholder="请选择新角色">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSetRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data () {
    // 定义校验邮箱规则
    const checkEmail = (r, v, cb) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(v)) {
        return cb()
      }
      cb(new Error('邮箱格式错误'))
    }
    // 定义手机号码校验规则
    const checkMobile = (r, v, cb) => {
      // rule: 当前的检验规则
      // value: 当前校验规则 检验的那个值
      // callback: 回调函数
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(v)) {
        return cb()
      }
      return cb(new Error('手机号码格式错误'))
    }
    return {
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      users: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加用户表单信息
      addForm: {
        username: 'adminone',
        password: 1234,
        email: 'admin@qq.com',
        mobile: 13945678911
      },
      editForm: {
        username: '哈哈哈',
        email: '哈123@qq.com',
        mobile: 15967891234
      },
      // 添加用户表单检验规则
      addRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // validate: function 进行自定义检验规则
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editRule: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // validate: function 进行自定义检验规则
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false,
      currentUser: {},
      roleList: [],
      selectValue: ''
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.users = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (val) {
      // console.log(val)
      this.queryData.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      // console.log(val)
      this.queryData.pagenum = val
      this.getUserList()
    },
    async stateChange (info) {
      // console.log(info)
      const { data: res } = await this.$axios.put(`users/${info.id}/state/${info.mg_state}`)
      // console.log(res)
      // console.log(info.mg_state)
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
    },
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 提交添加用户
    addUser () {
      this.$refs.addFormRef.validate(async flag => {
        if (!flag) return
        // console.log('将表单发给后台')
        const { data: res } = await this.$axios.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        // console.log(res)
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 点击编辑按钮
    editDialog (info) {
      this.editDialogVisible = true
      this.editForm = info
    },
    // 监听编辑对话框重置
    resetEdit () {
      //  注意 form表单上一定要有 ref=editFormRef 这个属性
      this.$refs.editFormRef.resetFields()
    },
    // 提交编辑用户
    editUser () {
      this.$refs.editFormRef.validate(async flag => {
        if (!flag) return
        // console.log('提交表单')
        const { data: res } = await this.$axios.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        // console.log(res)
        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    deleteUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '后台管理系统', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 点击了确认
          // console.log('确认删除')
          const { data: res } = await this.$axios.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message.success('删除成功')
          this.getUserList()
        })
        .catch(() => {
          // 点击了取消
          this.$message.info('已取消删除')
        })
    },
    async setRole (row) {
      this.setRoleDialogVisible = true
      this.currentUser = row
      // console.log(row)
      // console.log(this.currentUser)
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.roleList = res.data
    },
    // 点击确定分配角色
    async submitSetRoles () {
      if (this.selectValue === '') return this.$message.error('选择角色')
      const { data: res } = await this.$axios.put('users/' + this.currentUser.id + '/role', {
        rid: this.selectValue
      })
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.setRoleDialogVisible = false
      this.getUserList()
      this.$message.success('分配成功')
    },
    closesetRoles () {
      this.selectValue = ''
    }
  }
}
</script>

<style scoped lang='less'>

</style>
